import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router';
import { useMainStore } from '@/store/index.js';
import { routerList } from '@/utils/config';
// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// const _import = require('./import-' + process.env.NODE_ENV)
// 生产环境的为 file => () => import('@/views/' + file + '.vue')
// const _import = file => import.meta.glob('@/views/page/' + file + '/index.vue');
const modules = import.meta.glob('@/views/page/**/index.vue');
const _import = file => modules['@/views/page/'+file];



// 全局路由(无需嵌套上左右整体布局)
const globalRoutes: Array<RouteRecordRaw> = [
	{
		path: '/login',
		component: () => import('../views/global/LoginView.vue'),
		name: 'login',
		meta: {
			title: '登录'
		}
	}
];
// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
	path: '/',
	component: () => import('../views/global/MainView.vue'),
	name: 'main',
	redirect: {
		name: 'home'
	},
	meta: {
		title: '主入口整体布局'
	},
	children:fnAddDynamicMenuRoutes(routerList),
	// 加载页面之前判断是否为登录状态，从本地cookie获取token值，token不存在或token为空则清空登录信息且跳转去登陆页面
	beforeEnter(_to: any, _from: any, next: (arg0?: { name: string } | undefined) => void) {
		const mainStore = useMainStore();
		let token = mainStore.token;
		if (!token || !/\S/.test(token)) {
			// clearLoginInfo()
			next({
				name: 'login'
			});
			return;
		}
		next();
	}
};



// 路由对象
const router = createRouter({
	history: createWebHashHistory(),
	routes: globalRoutes.concat(mainRoutes)
});


function fnAddDynamicMenuRoutes(menuList) {
	const routes = []
	for (let i = 0; i < menuList.length; i++) {
		var route = {
			path: menuList[i].path,
			component: null,
			name: menuList[i].url.replace('/', '-'),
			meta: {
				menuId: menuList[i].name,
				title: menuList[i].title,
			}
		};
		try {
			const fn = ()=> import(`@/views/page/${menuList[i].url}/index.vue`)
			route['component'] = fn || null;
		} catch (e) {
			console.log(e);
		}
		routes.push(route)
	};
	console.log('routes',routes);
	return routes
}

export default router;
